##-----------------------------------------------------------------------
## "UpdateNuGetPackages.ps1"
##-----------------------------------------------------------------------
# Look for a packages.config files in the SourceCode tree. 
# If found, update using NuGet command.
#
Param(
  [string]$pathToSearch = $env:TF_BUILD_SOURCESDIRECTORY,
  [string]$searchFilter = "packages.config"
)

# Find the MSBuild.exe location
# Where this come from? valid versions are [2.0, 3.5, 4.0, 4.5]
$dotNetVersion = "4.0"
$regKey = "HKLM:\software\Microsoft\MSBuild\ToolsVersions\$dotNetVersion"
$regProperty = "MSBuildToolsPath"

$msbuildExe = join-path -path (Get-ItemProperty $regKey).$regProperty -childpath "msbuild.exe"
$updateTargets = $msbuildExe + " /t:UpdatePackages "

# Relevant for TFS, because all the checked out files are marked as Read-only.
# Find the packages.config and project configuration files location, and remove their read-only attribute flag.
Write-Host "Find the packages.config and project configuration files location, and remove their read-only attribute flag."
gci -Include packages.config, *.csproj -Recurse | % { if($_.IsReadOnly){$_.IsReadOnly= $false} }


Write-Host " Going to execute $($updateTargets)"

# Execute the NuGet command for each packages.config.
gci -Path $pathToSearch -Filter $searchFilter -Recurse | %{
        Write-Host "  -> Updating $($_.FullName)" 
		
		# execute nuget update command on each
		$folder = Split-Path $_.FullName
		cd $folder
		Invoke-Expression $updateTargets
		# &$msbuildExe /t:UpdatePackages
		# ..\.nuget\nuget.exe update packages.config -Safe -NonInteractive 

    Write-Host "Done!"
}